
import { userPermission } from '@/api/user'
import { setEnterTime } from '@/utils/auth.js'
import menuList from './menuList.json'
const state = {
  roleId: '',
  isShowHam: true, // 控制hamburger是否显示
  permissionRoutes: [],
  routesList: [],
  stageId_global: '',
  data_global: [],
  mapPermissionFun: new Map(),
  permissions: []
};

const mutations = {
  SET_MENU_LIST: (state, routes) => {
    state.permissionRoutes = routes
  },
  SET_PERMISSIONS: (state, permissions) => {
    state.permissions = permissions
  },
};

const actions = {
  // 获取路由权限
  getAllRouters({ commit }) {
    return new Promise((resolve) => {
      // getRouters().then((res) => {
      const res = menuList
      const _data = res.data || {}
      const sidebarRoutes = filterAsyncRouter(_data)
      commit("SET_MENU_LIST", sidebarRoutes);
      resolve(res)
      // });
    });
  },
  // 获取用户信息
  userPermission({ commit }) {
    return new Promise((resolve) => {
      userPermission().then((res) => {
        setEnterTime(Date.now())
        const _data = res.data || {}
        commit('SET_PERMISSIONS', _data.functionList)
        resolve(res)
      });
    });
  },
};

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap, lastRouter = false, type = false) {
  let result = []
  asyncRouterMap.forEach(item => {
    if (item.path && item.path === '/') {
      result = result.concat(item.children)
    } else {
      result.push(item)
    }
  })
  return result
}

export default {
  state,
  mutations,
  actions,
};
